package com.su.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.su.usercenter.common.ErrorCode;
import com.su.usercenter.exception.BusinessException;
import com.su.usercenter.mapper.UserMapper;
import com.su.usercenter.model.domain.User;
import com.su.usercenter.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.su.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author suhon
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-09-09 19:59:30
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    private UserMapper userMapper;

    /**
     * 设置“盐值”，混淆加密
     */
    private static final String SALT = "su";

    @Override
    public long Register(String account, String password, String checkPassword,String planetCode) {
        if(StringUtils.isAnyBlank(account,password,checkPassword,planetCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(account.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(password.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(planetCode.length() > 5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //账户只能包含数字和字母(必须包含一个数字和一个字母，长度1-9位)
        String validPatten = "^(?=.*\\d)(?=.*[A-z])[\\da-zA-Z]{1,9}$";
        Matcher matcher = Pattern.compile(validPatten).matcher(account);
        if(!matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询数据库操作，比较浪费性能，所以置后
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount",account);
        long count = userMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //查询数据库操作，星球编号不能重复
        queryWrapper = new QueryWrapper();
        queryWrapper.eq("planetCode",planetCode);
        count = userMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        if(!password.equals(checkPassword)){//判断字符串相等，不能用==
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //对密码进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //插入数据
        User user = new User();
        user.setUserAccount(account);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if(!saveResult){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return user.getId();//自动拆箱为long
    }

    @Override
    public User userLogin(String account, String password, HttpServletRequest request) {
        if(StringUtils.isAnyBlank(account,password)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(account.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(password.length()<8){
            return null;
        }
        //账户只能包含数字和字母(必须包含一个数字和一个字母，长度1-9位)
        String validPatten = "^(?=.*\\d)(?=.*[A-z])[\\da-zA-Z]{1,9}$";
        Matcher matcher = Pattern.compile(validPatten).matcher(account);
        if(!matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //将输入的密码进行加密，然后与数据库中存储的加密密码进行对比
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //在数据库中查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount",account);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //用户脱敏，创建返回给前端的用户,将从数据库中查到的可以返回的数据填入
        User safetyUser = getSafetyUser(user);
        //记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);

    return safetyUser;
    }
    @Override
    public User getSafetyUser(User orignUser){

        User safetyUser = new User();
        safetyUser.setId(orignUser.getId());
        safetyUser.setUsername(orignUser.getUsername());
        safetyUser.setUserAccount(orignUser.getUserAccount());
        safetyUser.setAvatarUrl(orignUser.getAvatarUrl());
        safetyUser.setGender(orignUser.getGender());
        safetyUser.setPhone(orignUser.getPhone());
        safetyUser.setEmail(orignUser.getEmail());
        safetyUser.setUserStatus(orignUser.getUserStatus());
        safetyUser.setCreatTime(orignUser.getCreatTime());
        safetyUser.setUserRole(orignUser.getUserRole());
        safetyUser.setPlanetCode(orignUser.getPlanetCode());
        return safetyUser;
    }

    /**
     * 用户注销
     * @param request
     */
    @Override
    public int logout(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
}




